package com.cmccgz.baselibrary.utils;

import java.security.MessageDigest;

public class MD5Utils {

	private final static char[] hexDigits = { '0', '1', '2', '3', '4', '5','6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

	public static String bytesToHex(byte[] bytes) {
		StringBuffer sb = new StringBuffer();
		int t;
		for (int i = 0; i < bytes.length; i++) {
			t = bytes[i];
			if (t < 0)
				t += 256;
			sb.append(hexDigits[(t >>> 4)]);
			sb.append(hexDigits[(t % 16)]);
		}
		return sb.toString();
	}

	public static String hexStr2Str(String hexStr)
    {    
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();    
        byte[] bytes = new byte[hexStr.length() / 2];    
        int n;    
  
        for (int i = 0; i < bytes.length; i++)  
        {    
            n = str.indexOf(hexs[2 * i]) * 16;    
            n += str.indexOf(hexs[2 * i + 1]);    
            bytes[i] = (byte) (n & 0xff);    
        }    
        return new String(bytes);
    }  
	/***
	 * 32位md5
	 * @param s
	 * @return
	 */
	public final static String LongMD5(String s) {
		byte[] strTemp = s.getBytes();
		MessageDigest mdTemp = null;
		try {
			mdTemp = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			return null;
		}
		mdTemp.update(strTemp);
		byte[] md = mdTemp.digest();
		int j = md.length;
		char str[] = new char[j * 2];
		int k = 0;
		for (int i = 0; i < j; i++) {
			byte byte0 = md[i];
			str[k++] = hexDigits[byte0 >>> 4 & 0xf];
			str[k++] = hexDigits[byte0 & 0xf];
		}
		return new String(str);
	}

	/**
	 * 十六位的MD5码
	 * 
	 * @param s
	 * @return
	 */
	public static byte[] MD5(byte[] strTemp) {
		MessageDigest mdTemp = null;
		try {
			mdTemp = MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			return null;
		}
		mdTemp.update(strTemp);
		byte[] md = mdTemp.digest();
		return md;
	}
	
	/**
	 * 16位 MD5
	 * @param s
	
	 * @return
	 */
	public final static String ShortMD5(String s) {
		String md5Str = LongMD5(s);
		md5Str = md5Str.substring(8, 24);
		//md5Str=md5Str.toLowerCase();
		return new String(md5Str);
	}
}
